package com.cloud.feignconsumer.controller;

import com.alibaba.fastjson.JSON;
import com.cloud.feignconsumer.service.NonRegisterService;
import com.cloud.feignconsumer.service.ProviderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author kangwen
 */
@Slf4j
@RestController
public class FeignConsumerController {

	@Resource
	private DiscoveryClient discoveryClient;
	/**
	 * 这儿可能会看到编译报错，因为编译阶段HelloService还没有实现，当在程序启动的时候会给创建并注入 helloService
	 * Feign会通过动态代理，帮我们生成实现类
	 */
	@Resource
	private ProviderService providerService;
	@Resource
	private NonRegisterService nonRegisterService;

	@GetMapping("/helloFeign")
	public String hello() {
		return providerService.hello();
	}


	@GetMapping("/helloFeignNoRegister")
	public String helloNoRegister() {
		return nonRegisterService.hello();
	}


	@GetMapping("/info")
	public String info() {
		StringBuilder builder = new StringBuilder("[");
		List<String> services = discoveryClient.getServices();
		for (String service : services) {
			List<ServiceInstance> instances = discoveryClient.getInstances(service);
			if (instances != null) {
				instances.forEach(i -> log.info(
						i.getServiceId() + "\t" + i.getHost() + "\t" + i.getPort() + "\t" + i.getScheme() + "\t" + i
								.getUri()));
			}
			builder.append(JSON.toJSONString(instances)).append(",");
		}
		builder.append("[]]");
		return builder.toString();
	}

	@GetMapping("/timeout/{ms}")
	public String timeout(@PathVariable Long ms) {
		return providerService.timeout(ms);
	}
}
